package com.struts.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ObjectFactory;
import com.struts.pojo.User;
import com.struts.service.UserService;
import com.struts.service.impl.UserServiceImpl;
import com.struts.utils.UploadUtil;

public class UserAction extends ActionSupport{
	
	private User user ;
	private File upload ; //上传文件内容
	private String uploadFileName ; //上传文件的名称
	private UserService userService = new UserServiceImpl() ;
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	
	/**
	 * 显示所有用户信息
	 * @return
	 */
	public String showAllUser() {
		List<User> users = userService.getAllUser() ;
		List<User> userList = new ArrayList<User>() ;
		for (User user : users) {
			String sex = user.getSex() ;
			if("1".equals(sex)) {
				user.setSex("男") ;
			} else if ("2".equals(sex)) {
				user.setSex("女") ;
			}
			userList.add(user) ;
		}
		ActionContext.getContext().put("userList", userList) ;
		return "userList" ;
	}
	
	/**
	 * 跳转到添加页面
	 * @return
	 */
	public String addUI() {
		return "addUI" ;
	}
	
	/**
	 * 添加用户
	 */
	public String addUser() {
		//上传文件
		String path = UploadUtil.saveUploadFile(upload) ;
		//将上传文件的绝对路径、文件名称保存到user中
		user.setPath(path) ;
		user.setFilename(uploadFileName) ;
		//保存user信息到数据库
		userService.saveUser(this.user) ;
		return "addUser";
	}

}
